package wodegua.d29_多线程;

import java.util.ArrayList;
import java.util.List;

/**
 * 第一题:分析以下需求，并用代码实现
 * 训练目标:掌握java中多线程基本使用
 * 需求描述:有100份礼品，小红，小明两人同时发送，当剩下的礼品小于10份的时候则不再送出，利用多线程模拟该过程并将线程的名称打印出来。并最后在控制台分别打印小红，小明各自送出多少分礼物。
 *
 */
public class d11_ThreadDemo1 {
    public static void main(String[] args) throws Exception {
        List<String> gift = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            gift.add("第" + i + "份");
        }
        MyRunnableDemo1 xh = new MyRunnableDemo1(gift);
        MyRunnableDemo1 xm = new MyRunnableDemo1(gift);

        Thread r1 = new Thread(xh,"小红");
        r1.start();
        Thread r2 = new Thread(xm,"小明");
        r2.start();

        r1.join();
        r2.join();
        System.out.println(gift.size());
        System.out.println(r1.getName() + "送出：" + xh.getCount());
        System.out.println(r2.getName() + "送出：" + xm.getCount());
    }
}

class MyRunnableDemo1 implements Runnable {
    private final List<String> gift;
    private int count;

    public MyRunnableDemo1(List<String> gift) {
        this.gift = gift;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (true) {
            synchronized (gift) {
                if (gift.size() < 10) {
                    break;
                }
                String g = gift.remove(0);
                System.out.println(name + g);
                count++;
            }
        }
    }
}
